package server.socket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DemoServerSocket {
	private int port;
	private boolean isStop = false;
	private ServerSocket serverSocket;
	private ExecutorService executor = Executors.newFixedThreadPool(200);
	
	public DemoServerSocket(int port){
		this.port = port;
	}
	
	public void create(){
		if (createServer()) {
			System.out.println("Tao server thanh cong");
			loop();
		}
	}
	
	private boolean createServer(){
		try {
			serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
		
	}
	
	private void loop(){
		while (!isStop) {
			try {
				Socket clientSocket = serverSocket.accept();
				DemoServerHandler serverHandler = new DemoServerHandler(clientSocket);
				executor.execute(serverHandler);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		executor.shutdown();
		System.out.println("server stop");
		
	}
	
	public boolean disconnect(){
		try {
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
